clear; %close all;

%%% PARAMETERS
NB=5;
alp=.1; %for parameter for A
bet=.5; %for parameter for B
k=1;
LB=[0]; UB=[1]; %% Lower bound for x and y

%% Utility maximization options
OPTIONS = OPTIMSET('Display','off','LargeScale','off');
   
for n=1:10
val(n)=n;
NA=val(n);

lam=1/(NA+NB); %% Initial guess for lambda
diff=1;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Solve for lambda
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while diff>.001

%% Given the initial guess for lambda, maximize the utility of A 
%% by making B indifferent between the role of divider and chooser   
Xtemp=FMINCON('auctionA',.01,[],[],[],[],LB,UB,[],OPTIONS,alp,bet,NA,NB,k,lam);

%% Equilibrium allocations
ya=Xtemp;
xa=1-NB*lam*( (1-k*(1-NB*lam))/(1-k*ya) )^((1-bet)/bet);

%% Utility of A if divider
Ua=xa^alp * (1 - k*(1-ya))^(1-alp);
%% Utility of A if chooser (at current lambda)
Ua_chooser = (NA*lam)^alp * (1 - k*(1-NA*lam))^(1-alp);

disp([NA Ua-Ua_chooser]);

%% If at the current lambda, A is getting a utility from being divider higher
%% than he would if he was a chooser, then it means that lambda is too low,
%% hence increase lambda. Otherwise decrease lambda.
diff=Ua-Ua_chooser;
if diff>=0
    lam=lam+.00001;
else
    lam=lam-.00001;
end

diff=abs(diff); %% if the two utilities are close enough, then we have converged

end


%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Now we check that at lambda that makes A indifferent between divider and
%% chooser, B is also indifferent between the two roles.
%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 1. Compute allocations if B is divider  
Xtemp=FMINCON('auctionB',.01,[],[],[],[],LB,UB,[],OPTIONS,alp,bet,NA,NB,k,lam);
yb=Xtemp;
xb=1-NA*lam*( (1-k*(1-NA*lam))/(1-k*yb) )^((1-alp)/alp);
%% 2. Compute utilities if he is divider and if he is chooser
Ub=xb^bet * (1-k*(1-yb))^(1-bet);
Ub_chooser = (NB*lam)^bet * (1 - k*(1-NB*lam))^(1-bet);
%% 3. Compare
if abs(Ub-Ub_chooser)<0.01
    disp('check on b: ok')
else
    disp('Error: increase accuracy')
    return
end

%% Store results
out(n,:)=[xa xb ya yb lam lam];
out2(n,:)=[(xa+ya)/2 (xb+yb)/2 lam NA/(NA+NB)];
end %% This ends loop on NA

re_we=val(:)./(val(:)+5);

%% Plot (foreign + domestic) ministers
figure(1)
plot(re_we, out2(:,1),'-g'), xlabel('Nominal Voting Weight'), ylabel('Share of cabinet seats'), 
hold on

